<script setup lang="ts">
import TableView from '@/components/TableView.vue'
import {
    NButton,
    NDataTable,
    NPagination,
    useMessage,
    NForm,
    NFormItem,
    type DataTableColumns,
    NSpace,
    NInput,
    NSelect,
    NDatePicker,
} from 'naive-ui'
import { h, ref, reactive, watch, onDeactivated } from 'vue'
import router from '@/router'
import { useRoute } from 'vue-router'
import { sendRequest } from '@/utils/api'
import { useViewerStore } from '../Common/store'

const message = useMessage()
const route = useRoute()
const useStore = useViewerStore()

const rowKey: any = (e: any) => e.id || ''
const columns: DataTableColumns = [
    {
        title: '来文文号',
        key: 'noCommunication',
        width: '5rem',
        align: useStore.isCenter,
        ellipsis: {
            tooltip: {
                contentStyle: {
                    maxWidth: '400rem'
                }
            }
        }
    },
    {
        title: '来文标题',
        key: 'titleCommunication',
        width: '10rem',
        align: useStore.isCenter,
        ellipsis: {
            tooltip: {
                contentStyle: {
                    maxWidth: '400rem'
                }
            }
        }
    },
    {
        title: '来文单位',
        key: 'unitCommunication',
        width: '10rem',
        align: useStore.isCenter,
        ellipsis: {
            tooltip: {
                contentStyle: {
                    maxWidth: '400rem'
                }
            }
        }
    },
    {
        title: '阅办类型',
        key: 'readType',
        width: '5rem',
        align: useStore.isCenter
    },
    {
        title: '状态',
        key: 'status',
        width: '5rem',
        align: useStore.isCenter,
        render(e: any) {
            return e.status == 'completed' ? '已完结' : '流转中'
        }
    },
    {
        title: '收文时间',
        key: 'timeReceipt',
        width: '10rem',
        align: useStore.isCenter
    },
    {
        title: '最后更新时间',
        key: 'nodeTime',
        width: '10rem',
        align: useStore.isCenter
    },
    {
        title: '操作',
        key: 'action',
        width: '15rem',
        align: useStore.isCenter,
        fixed: 'right',
        render: (e: any) => [
            h(
                NButton,
                {
                    type: 'primary',
                    quaternary: true,
                    onClick: () => handleDetail(e)
                },
                {
                    default: () => '详情'
                }
            ),
        ]
    }
]

//筛选条件
const formValue = reactive({
    titleCommunication: null, //来文标题
    visitUnit: null, //来文单位
    visitNumber: null, //来文文号
    readType: null, //阅办类型
    flowStatus: null, //流程状态
    receiveStartTime: null, //收文开始时间
    receiveEndTime: null //收文结束时间
})
const paginationReactive = reactive({
    page: 1,
    pageSize: 10,
    showSizePicker: true,
    pageSizes: [10, 20, 50, 100, 500],
    itemCount: 0,
    onChange: (page: number) => {
        paginationReactive.page = page
        queryTableData()
    },
    onUpdatePageSize: (pageSize: number) => {
        paginationReactive.pageSize = pageSize
        paginationReactive.page = 1
        queryTableData()
    }
})

//收文时间
const changeGetTime = (v: any) => {
    if (v) (formValue.receiveStartTime = v[0]), (formValue.receiveEndTime = v[1])
    else (formValue.receiveStartTime = null), (formValue.receiveEndTime = null)
}

const readingList = [
    {
        value: '阅办件',
        label: '阅办件'
    },
    {
        value: '阅知件',
        label: '阅知件'
    }
]

const transformList = [
    {
        value: 'pending',
        label: '流转中'
    },
    {
        value: 'completed',
        label: '已完结'
    }
]

//详情
const handleDetail = (val: any) => {
    router.push({
        path: '/OA/ReadingAndProcessing/ReadingDetail',
        query: {
            id: val.id,
            finish: true as never,
        }
    })
}

// 获取当前用户分身
// 机要：con
// 部门负责人：dep
// 普通员工：other
//nodeType : completed(未流转) / pending(已流转)
const userType: any = ref('')
const queryUser = async () => {
    const [error, res] = await sendRequest({
        module: 'readingandprocessing',
        api: 'userInfo',
    })
    if (error) return message.error(error.message)
    if (res.code) return message.error(res.msg)
    userType.value = res.data
}

//表格数据
const tableLoading = ref(false)
const tableData: any = ref([])
const queryTableData = async (resetPage = false) => {
    await queryUser()
    if (resetPage) paginationReactive.page = 1
    tableLoading.value = true
    if (userType.value == 'con') {
        const [error, res] = await sendRequest({
            module: 'readingandprocessing',
            api: 'ManageList',
            override: {
                params: {
                    ...formValue,
                    flowStatus: 'completed',
                    page: paginationReactive.page,
                    limit: paginationReactive.pageSize
                }
            }
        })
        tableLoading.value = false
        if (error) return message.error(error.message)
        paginationReactive.itemCount = res.data?.totalCount
        const tmp: any = res.data
        tableData.value = tmp?.list
    } else {
        const [error, res] = await sendRequest({
            module: 'readingandprocessing',
            api: 'List',
            override: {
                params: {
                    ...formValue,
                    isProcess: 1,
                    page: paginationReactive.page,
                    limit: paginationReactive.pageSize
                }
            }
        })
        tableLoading.value = false
        if (error) return message.error(error.message)
        paginationReactive.itemCount = res.data?.totalCount
        const tmp: any = res.data
        tableData.value = tmp?.list
    }
    tableLoading.value = false
}

const keyUpDown = (e: any) => e.key == 'Enter' && (paginationReactive.page = 1,queryTableData(true))
onDeactivated(() => window.removeEventListener('keyup', keyUpDown, false))


watch(
    () => route.path,
    async () => {
        if (route.path == '/OA/ReadingAndProcessing/ReadList') {
            await queryTableData()
            window.addEventListener('keyup', keyUpDown, false)
        }
    },
    { deep: true, immediate: true }
)
</script>

<template>
    <TableView class="table">
        <template #form>
            <NSpace justify="space-between">
                <NForm :show-feedback="false" label-placement="left" inline>
                    <NFormItem label="来文标题:">
                        <NInput clearable placeholder="请输入来文标题" v-model:value="formValue.titleCommunication" />
                    </NFormItem>
                    <NFormItem label="来文单位:">
                        <NInput clearable placeholder="请输入来文单位" v-model:value="formValue.visitUnit" />
                    </NFormItem>
                    <NFormItem label="来文文号:">
                        <NInput clearable placeholder="请输入来文文号" v-model:value="formValue.visitNumber" />
                    </NFormItem>
                    <NFormItem label="阅办类型:">
                        <NSelect clearable placeholder="请选择阅办类型" style="width: 180rem" :options="readingList"
                            v-model:value="formValue.readType"  />
                    </NFormItem>
                    <NFormItem label="状态:">
                        <NSelect clearable placeholder="请选择状态" style="width: 180rem" :options="transformList"
                            v-model:value="formValue.flowStatus"  />
                    </NFormItem>
                    <NFormItem label="收文时间:">
                        <NDatePicker input-readonly class="commonWidth" type="datetimerange" default-time="00:00:00"
                            @update-formatted-value="changeGetTime" clearable />
                    </NFormItem>
                </NForm>
                <NSpace align="end">
                    <NButton type="primary" ghost @click="queryTableData(true)" style="width: 80px;">
                        查询
                    </NButton>
                </NSpace>
            </NSpace>
        </template>

        <template #table="props">
            <NDataTable v-bind="props" :bordered="false" :row-key="rowKey" :columns="columns" :data="tableData"
                :loading="tableLoading" />
        </template>

        <template #pagination>
            <NPagination :page-sizes="paginationReactive.pageSizes" :item-count="paginationReactive.itemCount"
                :page="paginationReactive.page" :page-size="paginationReactive.pageSize"
                @update:page="paginationReactive.onChange" @update:page-size="paginationReactive.onUpdatePageSize"
                show-size-picker show-quick-jumper :suffix="() => '页'">
                <template #prefix>
                    <span style="font-size: 14px;"> 共{{ paginationReactive.itemCount }}条</span>
                </template>
            </NPagination>
        </template>
    </TableView>
</template>

<style scoped lang="scss">
.table {
    height: 100%;
    padding: 29px 30px 42px;
}
</style>
